<template>
  <div class="user-profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人信息管理</h2>
          <el-tag :type="userRoleTagType">{{ userForm.userRole === 'doctor' ? '医生' : '管理员' }}</el-tag>
        </div>
      </template>

      <el-form 
        :model="userForm" 
        label-width="100px" 
        :rules="rules"
        ref="userFormRef"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="userForm.userName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="userForm.realName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="telephone">
              <el-input v-model="userForm.telephone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后登录" prop="lastLogin">
              <el-input :value="formatDate(userForm.lastLogin)" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading.saveInfo">
            {{ loading.saveInfo ? '保存中...' : '保存信息' }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="warning" @click="showPasswordDialog = true">
            修改密码
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog 
      v-model="showPasswordDialog" 
      title="修改密码" 
      width="30%"
      :before-close="handleCloseDialog"
    >
      <el-form 
        :model="passwordForm" 
        :rules="passwordRules" 
        ref="passwordFormRef"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password" 
            show-password
            placeholder="请输入当前密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            show-password
            placeholder="6-16位字母数字组合"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            show-password
            placeholder="再次输入新密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitPassword"
          :loading="loading.changePassword"
        >
          {{ loading.changePassword ? '修改中...' : '确认修改' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const API_PREFIX = 'http://localhost:8080/hospital5'

const userStore = useUserStore()
const userFormRef = ref()
const passwordFormRef = ref()
const showPasswordDialog = ref(false)

const loading = reactive({
  saveInfo: false,
  changePassword: false
})

// 用户表单数据
const userForm = reactive({
  userId: '',
  userName: '',
  realName: '',
  telephone: '',
  userRole: '',
  lastLogin: null
})

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 计算角色标签类型
const userRoleTagType = computed(() => {
  return userForm.userRole === 'doctor' ? 'success' : 'warning'
})

// 表单验证规则
const rules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
  ],
  telephone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在6到16个字符', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!/^(?=.*[a-zA-Z])(?=.*\d).+$/.test(value)) {
          callback(new Error('密码必须包含字母和数字'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
}

// 验证两次密码是否一致
function validatePassword(rule, value, callback) {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '暂无记录'
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 初始化用户数据
onMounted(() => {
  if (userStore.userInfo) {
    Object.assign(userForm, userStore.userInfo)
  }
})

// 提交用户信息
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.saveInfo = true
      try {
        const response = await axios.post(`${API_PREFIX}/user/updateUserInfo`, userForm)
        if (response.status === 200) {
          ElMessage.success('个人信息更新成功')
          // 更新store中的用户信息
          userStore.setUserInfo(userForm)
        }
      } catch (error) {
        ElMessage.error('更新失败: ' + (error.response?.data?.message || error.message))
      } finally {
        loading.saveInfo = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (userStore.userInfo) {
    Object.assign(userForm, userStore.userInfo)
    ElMessage.info('已重置为原始信息')
  }
}

// 关闭密码对话框前的处理
const handleCloseDialog = () => {
  if (passwordForm.oldPassword || passwordForm.newPassword || passwordForm.confirmPassword) {
    ElMessageBox.confirm('确定放弃修改密码吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      passwordFormRef.value.resetFields()
      showPasswordDialog.value = false
    })
  } else {
    showPasswordDialog.value = false
  }
}

// 提交密码修改
const submitPassword = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.changePassword = true
      try {
        const params = {
          userId: userForm.userId,
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        }
        
        const response = await axios.post(`${API_PREFIX}/user/updatePassword`, params)
        
        if (response.data?.success) {
          ElMessage.success('密码修改成功')
          passwordFormRef.value.resetFields()
          showPasswordDialog.value = false
        } else {
          ElMessage.error(response.data?.message || '密码修改失败')
        }
      } catch (error) {
        ElMessage.error('修改失败: ' + (error.response?.data?.message || error.message))
      } finally {
        loading.changePassword = false
      }
    }
  })
}
</script>

<style scoped>
.user-profile-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.el-tag {
  margin-left: 10px;
}
</style>